<?php

# Import the application settings.
require_once(dirname(__FILE__) . '/config.php');

# Import the products.
include(APPLICATION_ROOT . '/items.php');

# Make sure we're not trying to use this script without any input.
if ((!$_GET['id']) AND (!$_GET['c'])) {
	# No vars, no service.
	die('No input supplied.');
}

# Sanitize the inputs.

$action = filter_input(INPUT_GET, 'c', FILTER_SANITIZE_STRING);
$format = filter_input(INPUT_GET, 'f', FILTER_SANITIZE_STRING);
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$price = (float)filter_input(INPUT_GET, 'price', FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
$referer = filter_input(INPUT_SERVER, 'HTTP_REFERER', FILTER_SANITIZE_URL);

# Are we adding something to the cart?
if ($action != "cart") {
	# Yes, we're adding something to the cart.

	# Ensure that the product ID is valid.
	if (!array_key_exists($id, $products)) {
		die('Invalid product specified.');
	}

	$product = $products[$id];

	# Extract the product prices and formats.
	$product_prices = array_key_exists('price', $product) ? $product['price'] : Array('0');
	$product_formats = array_key_exists('formats', $product) ? $product['formats'] : Array('Any');

	$formats = split(',', $product_formats);
	$prices  = split(',', $product_prices);

	# Ensure that the given price is valid for this product.
	$matched_price = FALSE;
	foreach ($prices as $allowed_price) {
		$allowed_price = (float)trim($allowed_price);
		if ($price == $allowed_price) {
			$matched_price = TRUE;
		}
	}
	if (!$matched_price) {
		die("Invalid price $price given.");
	}

	# Generate a drop down box for the formats, with the selected format selected.
	$format_form = '<input type="hidden" name="on0" value="Format"><select name="os0">';

	$format = trim($format);
	$matched_format = FALSE;
	foreach ($formats as $key => $allowed_format) {
		$SELECTED = NULL;
		$allowed_format = trim($allowed_format);

		# Only add this format if the user has entered format extension details for it.
		if (array_key_exists($allowed_format, $product)) {
			if ($format == $allowed_format) {
				$SELECTED = "SELECTED";
				$matched_format = TRUE;
			}

			$format_form .= '<option ' . $SELECTED . ' value="' . htmlentities($allowed_format) . '">' . htmlentities($allowed_format);
		}
	}

	$format_form .= '</select>';

	# Ensure that the given format is valid for this product.
	if (!$matched_format) {
		die("Invalid format $format given.");
	}

	# Are we using the PayPal cart or the BSDDS cart?
	if (BSDDS_CART == "BSDDS") {
		# We're using the BSDDS cart.
		# Retrieve some product details (such as shipping costs) to put into the cart.
		$storename = htmlentities(BSDDS_STORENAME);
		$web_root = WEB_ROOT;
		$paypal_email = PAYPAL_EMAIL;
		$currency = htmlentities(BSDDS_CURRENCY);
		$out_price = htmlentities($price);
		$product_name = array_key_exists('name', $product) ? htmlentities($product['name']) : 'Unknown product';
		$product_id = htmlentities($id);
		$shipping_cad = array_key_exists('shipping_cad', $product) ? $product['shipping_cad'] : 0;
		$shipping_int = array_key_exists('shipping_int', $product) ? $product['shipping_int'] : 0;
		$shipping_usd = array_key_exists('shipping_usd', $product) ? $product['shipping_usd'] : 0;
		$shipping_each = array_key_exists('shipping_each', $product) ? $product['shipping_each'] : 0;
		print <<<HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>                                                                                                                      
    <head>                                                                                                                  
        <title>$storename</title>                                                         
    </head>
	<body onload="document.bsdds.submit();">
		<form action="${web_root}cart/cart.php" name="bsdds" method="POST">
			<input type="hidden" name="business" value="$paypal_email">
			<input type="hidden" name="item_name" value="$product_name">
			<input type="hidden" name="item_number" value="$product_id">
			<input type="hidden" name="quantity" value="1">
			<input type="hidden" name="shipping_usd" value="$shipping_usd">
			<input type="hidden" name="shipping_cad" value="$shipping_cad">
			<input type="hidden" name="shipping_int" value="$shipping_int">
			<input type="hidden" name="shipping_each" value="$shipping_each">
			<input type="hidden" name="tax" value="0">
			<input type="hidden" name="return_url" value="{$referer}">
			<input type="hidden" name="custom" value="">
			<input type="hidden" name="currency_code" value="$currency">
			<input type="hidden" name="amount" value="{$out_price}" size="4" />
			${format_form}
			<input type="hidden" name="add_cart" value="Add product to cart " />
		</form>
	</body>
</html>
HTML;
		die();
	}
} else {
	# We're viewing the cart.

	# Are we viewing the BSDDS cart?
	if (BSDDS_CART == "BSDDS") {
		# Redirect to the BSDDS cart.
		header('Location: ' . WEB_ROOT . 'cart/cart.php');
	} elseif (BSDDS_CART == "PayPal") {
		# Use a PayPal submission method via Javascript.
		$storename = htmlentities(BSDDS_STORENAME);
		$web_root = WEB_ROOT;
		$paypal_email = PAYPAL_EMAIL;
		$paypal_url = PAYPAL_URL;
		print <<<HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>                                                                                                                      
    <head>                                                                                                                  
        <title>$storename</title>                                                         
    </head>
	<body onload="document.paypal.submit();">
		<span style="visibility: hidden;">
			<form name="paypal" target="paypal" action="https://${paypal_url}/cgi-bin/webscr" method="post">
				<input type="hidden" name="cmd" value="_cart">
				<input type="hidden" name="business" value="${paypal_email}">
				<input type="image" src="https://${paypal_url}/en_US/i/btn/view_cart.gif" border="0" name="submit" alt="Make payments with PayPal - it\'s fast, free and secure!">
				<input type="hidden" name="display" value="1">
			</form>
		</span>
	</body>
</html>
HTML;
	}
}